package net.htjs.juc.chapter04;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DemoSynchronizedFor {

    static int counter = 0;
    static final Object object = new Object();

    /**
     * 线程1运行完,线程2再运行，Synchronized包裹的代码具有原子性，不可分割
     * @param args
     */
    public static void main(String[] args) {
        try {
            Thread t1 = new Thread(() -> {
                synchronized (object) {
                    for (int i = 0; i < 10000; i++) {
                        counter++;
                        log.info("counter:{}", counter);
                    }
                }
            }, "t1");
            Thread t2 = new Thread(() -> {
                synchronized (object) {
                    for (int i = 0; i < 10000; i++) {
                        counter--;
                        log.info("counter:{}", counter);
                    }
                }
            }, "t2");
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            log.info("counter:{}", counter);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
